import Vue from 'vue'
import Tips from './utils/tips.js'
import {
	// ApiUrl,
	// loginUrl,
	Url
} from './config.js';
const openWin = (_url, item) => {
	if (_url == '' || _url == null) {
		uni.showToast({
			title: '敬请期待',
			icon: "none",
			duration: 1000
		})
		return false
	}
	if (item) {
		let res = getUserInfo()
		console.log(res)
		let obj = {
			userId: res.userId,
			appid: item.id
		}
		ajax({
			url: '/userAppCommony/add',
			method: 'POST',
			data: obj,
			success: res => {
				console.log(res)
				if (res.code == 0) {

				}
			}
		})
	}
	uni.navigateTo({
		url: _url,
		animationType: 'pop-in',
		animationDuration: 10
	})
}
const login = () => {
	uni.showModal({
		title: '登录超时',
		content: '请重新登录',
		showCancel: false,
		success: (res) => {
			if (res.confirm) {
				signOut()
				return false
			}
		}
	});
}
// 定义常量
export const USER_INFO = 'user_info' // 用户信息
export function getUserInfo() {
	return uni.getStorageSync(USER_INFO) || null
}

export function setUserInfo(data) {
	return uni.setStorageSync(USER_INFO, data)
}

export function delUserInof() {
	return uni.removeStorageSync(USER_INFO)
}
const isLoginFn = () => {
	const result = uni.getStorageSync('token') || null //是否登录
	console.log(result)
	const isLogin = result ? true : false
	console.log(isLogin)
	return isLogin

}
const isges = () => {
	let userinfo = uni.getStorageSync('login_info') 
	console.log(userinfo)
	let res = uni.getStorageSync(userinfo.userid)
	let type = uni.getStorageSync('type')
	let typeone = uni.getStorageSync('fingerStatus')
	let unlocktypezw = uni.getStorageSync("unlockzw")
	let unlocktypesh = uni.getStorageSync("unlocksh")
	console.log(res)
	console.log(unlocktypesh)
	if (res.type || res.typeone ) {
		if (res.type && res.unlocksh) {
			let isgesture = res.pwd
			uni.reLaunch({
				url: `/pages/my/setgesture/setgesture?type=${1}&pwd=${isgesture}`,
			})
		} else if (res.typeone && res.unlockzw) {
			uni.reLaunch({
				url: "/pages/my/authfingerprint/authfingerprint",
			})
		}else {
			console.log("2")
			uni.reLaunch({
				url: "/pages/login/login",
			})
		}

	} else {
		uni.showToast({
			icon: 'none',
			title: '请先开启手势密码验证',
			duration: 2000,
		})
		uni.navigateTo({
			url: '/pages/my/gesture/gesture'
		})
	}
}
const ajax = (opt) => {
	// ajaxRequest(opt)
	console.log(opt)
	uni.getNetworkType({
		success: function(res) {
			console.log(res)
			if (res.networkType == 'none') {
				uni.stopPullDownRefresh()
				uni.showToast({
					title: '网络请求失败，请查询网络是否开启',
					icon: 'none',
					duration: 1000
				})
				setTimeout(function() {
					uni.hideToast()
				}, 1000)
			} else {
				ajaxRequest(opt)
			}
		}
	});
}
const ajaxRequest = (opt) => {
	let info = uni.getStorageSync('user');
	let token = uni.getStorageSync('token').token
	console.log(info)
	console.log(opt)
	let timer;
	let _url;
	const opts = {};
	console.log(opt, '344444')
	opts.url = opt.url || '';
	opts.data = opt.data || null;
	opts.method = opt.method || 'GET';
	opts.header = opt.header || {
		"accessToken": token,
		"pid": info.uuid
	};
	if (opt.contentType || opt.accessToken) {
		opts.header["Content-Type"] = opt.contentType
		// opts.header["accessToken"] = opt.accessToken
	} else {
		opts.header["Content-Type"] = "application/json"
	}

	if (opt.url.indexOf('/getToken') != -1 || opt.url.indexOf('/out') != -1 || opt.url.indexOf('/deToken') != -1) {
		_url = Url + opts.url
	} else if (opt.url.indexOf('/mpAppList/list') != -1 || opt.url.indexOf('/mpAppList/save') != -1 || opt.url.indexOf(
			'/upload/save') != -1) {
		_url = Url + opts.url
	} else {
		_url = Url + opts.url
	}
	opts.success = opt.success || function() {};
	uni.request({
		url: _url,
		data: opts.data,
		method: opts.method,
		header: opts.header,
		dataType: 'json',
		success: function(res) {
			// console.log('common request', res)
			uni.stopPullDownRefresh()
			Tips.loaded()
			if (res.data.code == -1) {
				setTimeout(() => {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1500
					});
				}, 100)
			} else {
				if (res.statusCode == 200) {
					opt.success(res.data);
				} else {
					uni.showToast({
						title: '服务异常,请联系管理员',
						icon: 'none',
						duration: 2000
					})
				}
			}
		},
		fail: function(err) {
			uni.hideLoading()
			uni.stopPullDownRefresh()
			uni.showToast({
				title: '网络异常,请检查网络',
				icon: 'none',
				duration: 2000
			})
		},
		complete: function(complete) {
			// uni.stopPullDownRefresh()
			// Tips.loaded()
		}
	})
}

const uploadImg = (opt) => {
	opt = opt || {};
	opt.count = opt.count || 1;
	opt.sizeType = opt.sizeType || ['compressed'];
	opt.sourceType = opt.sourceType || ['camera'];
	opt.success = opt.success || function() {};
	let _link = ''
	if (opt.type == 'information') {
		_link = ApiUrl + '/upload/qiniu'
	} else {
		// _link = ApiUrl + '/upload'  
		_link = Url + '/upload/save'
	}
	uni.chooseImage({
		count: opt.count, //默认9
		sizeType: opt.sizeType, //可以指定是原图还是压缩图，默认二者都有
		sourceType: opt.sourceType,
		success: (res) => {
			let info = uni.getStorageSync('user');
			let token = uni.getStorageSync('token').token
			const tempFilePaths = res.tempFilePaths;
			const uploadTask = uni.uploadFile({
				url: _link,
				header: {
					"accessToken": token,
					"pid": info.uuid
				},
				filePath: tempFilePaths[0],
				name: 'image',
				success: (uploadres) => {
					console.log(uploadres)
					if (uploadres.statusCode == 200) {
						let uploadobj = JSON.parse(uploadres.data)
						console.log(uploadobj)
						if (uploadobj.code == 1) {
							if (opt.type == 'information') {
								opt.success(uploadobj.data.img_url, uploadobj.data.img);
							} else {
								opt.success(uploadobj.data.img_url, tempFilePaths[0]);
							}
						} else {
							uni.showToast({
								title: uploadobj.message,
								icon: 'none',
								duration: 2000
							})
						}
					}
				},
				fail: () => {
					uni.showToast({
						title: '网络异常,请检查网络',
						icon: 'none',
						duration: 2000
					})
				},
				complete: () => {
					uni.hideLoading()
				}
			});
		}
	});
}
const saveImg = (_file) => {
	uni.hideLoading();
	uni.saveImageToPhotosAlbum({ //保存图片
		filePath: _file,
		success: (res) => {
			console.log(JSON.stringify(res));
			uni.showToast({
				title: '保存成功',
				icon: 'none',
				duration: 1000,
				mask: true
			})
		}
	})
}
const txtCopy = (_txt) => {
	return new Promise((resolve, reject) => {
		uni.setClipboardData({
			data: _txt,
			success: () => {
				uni.showToast({
					title: "复制成功",
					duration: 1000,
					icon: true
				})
				resolve()
			}
		});
	})
}
const versionCompare = function(curr, promote) {
	let currVer = curr || '0.0.0';
	let promoteVer = promote || '0.0.0';
	if (currVer === promoteVer) return false;
	let currVerArr = currVer.split('.');
	let promoteVerArr = promoteVer.split('.');
	let len = Math.max(currVerArr.length, promoteVerArr.length);
	let proVal, curVal;
	for (var i = 0; i < len; i++) {
		proVal = ~~promoteVerArr[i];
		curVal = ~~currVerArr[i];
		if (proVal < curVal) {
			return false;
		} else if (proVal > curVal) {
			return true;
		}
	}
	return false;
};
export {
	openWin,
	isges,
	ajax,
	isLoginFn,
	uploadImg,
	saveImg,
	txtCopy,
	versionCompare
}
